package com.company.calendar.controller;

import com.company.calendar.service.ExcelService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * Excel控制器
 * 
 * @author System
 * @since 1.0.0
 */
@RestController
@RequestMapping("/excel")
@RequiredArgsConstructor
@Slf4j
public class ExcelController {
    
    private final ExcelService excelService;
    
    /**
     * 导入节假日Excel文件
     * 
     * @param file Excel文件
     * @param companyId 公司ID
     * @return 导入结果
     */
    @PostMapping("/import/holidays")
    public ResponseEntity<Map<String, Object>> importHolidays(@RequestParam("file") MultipartFile file,
                                                             @RequestParam("companyId") Long companyId) {
        log.info("导入节假日Excel文件: 公司ID={}, 文件名={}", companyId, file.getOriginalFilename());
        
        // 验证文件类型
        String fileName = file.getOriginalFilename();
        if (fileName == null || (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls"))) {
            throw new RuntimeException("只支持Excel文件格式(.xlsx, .xls)");
        }
        
        // 验证文件大小
        if (file.getSize() > 10 * 1024 * 1024) { // 10MB
            throw new RuntimeException("文件大小不能超过10MB");
        }
        
        Map<String, Object> result = excelService.importHolidays(file, companyId);
        return ResponseEntity.ok(result);
    }
    
    /**
     * 导出节假日Excel文件
     * 
     * @param companyId 公司ID
     * @param year 年份
     * @return Excel文件
     */
    @GetMapping("/export/holidays")
    public ResponseEntity<byte[]> exportHolidays(@RequestParam Long companyId,
                                               @RequestParam(required = false) Integer year) {
        log.info("导出节假日Excel文件: 公司ID={}, 年份={}", companyId, year);
        
        // 如果没有指定年份，使用当前年份
        if (year == null) {
            year = java.time.Year.now().getValue();
        }
        
        byte[] excelData = excelService.exportHolidays(companyId, year);
        
        String fileName = String.format("节假日_%d_%d.xlsx", companyId, year);
        
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(excelData);
    }
    
    /**
     * 下载节假日导入模板
     * 
     * @return Excel模板文件
     */
    @GetMapping("/template/holidays")
    public ResponseEntity<byte[]> downloadHolidayTemplate() {
        log.info("下载节假日导入模板");
        
        // 创建模板文件
        byte[] templateData = createHolidayTemplate();
        
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=节假日导入模板.xlsx")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(templateData);
    }
    
    /**
     * 创建节假日导入模板
     * 
     * @return 模板文件字节数组
     */
    private byte[] createHolidayTemplate() {
        try (org.apache.poi.xssf.usermodel.XSSFWorkbook workbook = new org.apache.poi.xssf.usermodel.XSSFWorkbook()) {
            org.apache.poi.ss.usermodel.Sheet sheet = workbook.createSheet("节假日模板");
            
            // 创建标题行
            org.apache.poi.ss.usermodel.Row headerRow = sheet.createRow(0);
            String[] headers = {"节假日名称", "日期", "类型编码", "是否工作日", "描述"};
            
            for (int i = 0; i < headers.length; i++) {
                org.apache.poi.ss.usermodel.Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                
                // 设置标题样式
                org.apache.poi.ss.usermodel.CellStyle headerStyle = workbook.createCellStyle();
                org.apache.poi.ss.usermodel.Font headerFont = workbook.createFont();
                headerFont.setBold(true);
                headerStyle.setFont(headerFont);
                cell.setCellStyle(headerStyle);
            }
            
            // 添加示例数据
            org.apache.poi.ss.usermodel.Row exampleRow1 = sheet.createRow(1);
            exampleRow1.createCell(0).setCellValue("元旦");
            exampleRow1.createCell(1).setCellValue("2024-01-01");
            exampleRow1.createCell(2).setCellValue("LEGAL_HOLIDAY");
            exampleRow1.createCell(3).setCellValue("否");
            exampleRow1.createCell(4).setCellValue("新年第一天");
            
            org.apache.poi.ss.usermodel.Row exampleRow2 = sheet.createRow(2);
            exampleRow2.createCell(0).setCellValue("春节");
            exampleRow2.createCell(1).setCellValue("2024-02-10");
            exampleRow2.createCell(2).setCellValue("LEGAL_HOLIDAY");
            exampleRow2.createCell(3).setCellValue("否");
            exampleRow2.createCell(4).setCellValue("农历新年");
            
            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }
            
            // 转换为字节数组
            java.io.ByteArrayOutputStream outputStream = new java.io.ByteArrayOutputStream();
            workbook.write(outputStream);
            return outputStream.toByteArray();
            
        } catch (Exception e) {
            log.error("创建节假日导入模板失败", e);
            throw new RuntimeException("创建模板文件失败: " + e.getMessage());
        }
    }
}


